package com.linck.im.client.initial;

import com.linck.im.client.handler.ClientFriendsHandler;
import com.linck.im.client.handler.ClientHeartBeatHandler;
import com.linck.im.client.handler.ClientMessageHandler;
import com.linck.im.client.handler.ClientSysMsgHandler;
import com.linck.im.model.proto.ProtoMsg;
import com.linck.im.parse.decode.PackageDecode;
import com.linck.im.parse.encode.PackageEncode;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author: linck
 * @create: 2021-01-25
 */
public class ChatClientInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        // tcp拆包粘包处理
        pipeline.addLast(new LengthFieldPrepender(2));
        pipeline.addLast(new ProtobufEncoder());
        pipeline.addLast(new PackageEncode());

        // tcp拆包粘包处理
        pipeline.addLast(new LengthFieldBasedFrameDecoder(65536, 0, 2, 0, 2));
        pipeline.addLast(new ProtobufDecoder(ProtoMsg.Package.getDefaultInstance()));
        pipeline.addLast(new PackageDecode());
        // 心跳检测 写空闲10s，触发userEventTriggered
        pipeline.addLast(new IdleStateHandler(0, 10, 0, TimeUnit.SECONDS));
        pipeline.addLast(new ClientHeartBeatHandler());
        pipeline.addLast(new ClientFriendsHandler());
        pipeline.addLast(new ClientMessageHandler());
        pipeline.addLast(new ClientSysMsgHandler());
    }
}
